<template>
  <div class="dynamic_form_wrapper" :class="{ dynamic_form_table: props.config.style === 'table-form', dynamic_form_show: isMore }">
    <div class="dynamic_form_more">
      <a-button type="primary" @click="search()">查询</a-button>
      <a-button @click="reset()">重置</a-button>
      <span v-if="isHiddenMore" @click="isMore = !isMore">{{ isMore?'展开':'收起' }}<i class="iconfont icon-a-chevron-rightdouble"></i></span>
    </div>
    <!-- <h4 class="dynamic_h4" v-if="props.config.title">{{ props.config.title }}</h4> -->
    <a-form
      ref="formRef"
      @finishFailed="onFinishFailed"
      :hideRequiredMark="props.config.isView ? true : false"
      :scrollToFirstError="true"
      :model="ruleForm"
      :name="props.config.name ? props.config.name : 'dynamic_rule'"
      :layout="props.config.layout || 'horizontal'"
      v-bind="formItemLayout"
      :rules="rules"
    >
      <a-row :gutter="24">
        <template v-for="(question, index) in props.questions" :key="index">
          <template v-if="(question.controlType === 'title' || question.controlType === 'icons') && !question.hidden">
            <template v-if="question.type === 'slot'">
              <div class="dynamic_title">
                <slot :name="question.state.slotName" :data="ruleForm" :question="question"></slot>
              </div>
            </template>
            <component v-else v-bind:is="tagName(question.controlType)" :question="question" v-model:formData="ruleForm" @shrinkMethod="shrinkMethod(index, question)"> </component>
          </template>
          <a-col
            v-else
            :span="question.state.grid ? question.state.grid : props.config.grid ? props.config.grid : props.config.style === 'table-form' ? 8 : 24"
            v-show="!(question.hidden || question.hide)"
          >
            <div :class="{ full_line: question.state.fullLine ? true : false }" :style="{ width: question.state.width || 'auto', 'padding-right': question.state.width ? '12px' : '' }">
              <!-- 本地插槽 -->
              <template v-if="question.type === 'slot'">
                <a-form-item :name="question.key">
                  <template v-slot:label>
                    <label for="">{{ question.label }}</label>
                  </template>
                  <slot :name="question.state.slotName" :data="ruleForm" :question="question"></slot>
                </a-form-item>
              </template>
              <component
                v-else
                :config="props.config"
                :dataForm="dataForm"
                v-bind:is="tagName(question.controlType)"
                :question="question"
                v-model:formData="ruleForm[question.key]"
                :ref="(el) => handleRef(el, question)"
                @autoSearch="search"
                @parentServe="parentServe"
              >
              <!-- <template v-if="question.state.columns && question.state.columns.length && Array.isArray(question.state.columns)"> -->
                <template v-for="(item, idx) in question.state.columns" :key="idx" v-slot:[item.key]="{index}">
                  <a-form-item :name="item.key">
                    <slot :name="item.key" :data="ruleForm" :question="question.value[index]" :index="index"></slot>
                  </a-form-item>
                </template>
              <!-- </template> -->
              </component>
            </div>
          </a-col>
        </template>
      </a-row>
      <a-row v-if="!props.config.cancelSave">
        <a-col :span="24">
          <template v-if="props.config.style !== 'table-form'">
            <div class="footer_btns" :style="{ 'text-align': props.config.btnPosition ? props.config.btnPosition : 'right' }">
              <a-button @click="back()">{{ props.config.cancelText || '取消' }}</a-button>
              <slot name="footerBtn" :data="ruleForm"></slot>
              <a-button v-permission="props.config.key" v-if="!props.config.cancelSubmint" :loading="loading" type="primary" @click="onFinish()">{{ props.config.okText || '提交' }}</a-button>
            </div>
            <!-- <a-button type="primary" html-type="submit" >{{ props.config.okText || '提交' }}</a-button> -->
          </template>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import router from '@/router';
import { getCurrentInstance, ref, markRaw, onMounted, onUnmounted, reactive, nextTick, computed } from 'vue';
import { message, Form, FormInstance } from 'ant-design-vue';
import { ConfigBase, QuestionBase } from '../question-base';
import { useRoute } from 'vue-router';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import InputItem from './dynamic-form-question/input-item/input-item.component.vue';
import InputText from './dynamic-form-question/input-text/input-text.component.vue';
import InputRadio from './dynamic-form-question/input-radio/input-radio.component.vue';
import InputSelect from './dynamic-form-question/input-select/input-select.component.vue';
import InputSwitch from './dynamic-form-question/input-switch/input-switch.component.vue';
import InputCheckbox from './dynamic-form-question/input-checkbox/input-checkbox.component.vue';
import InputUpload from './dynamic-form-question/input-upload/input-upload.component.vue';
import InputTime from './dynamic-form-question/input-time/input-time.component.vue';
import InputCascader from './dynamic-form-question/input-cascader/input-cascader.component.vue';
import InputRelateBtn from './dynamic-form-question/input-relateBtn/input-relateBtn.component.vue';
import InputCustomTable from './dynamic-form-question/input-customTable/input-customTable.component.vue';
import InputCkeditor from './dynamic-form-question/input-ckeditor/input-ckeditor.component.vue';
import InputTitle from './dynamic-form-question/input-title/input-title.component.vue';
import InputIcons from './dynamic-form-question/input-icons/input-icons.component.vue';
import { DYNAMICLAYERCLEAR, DYNAMICTITLESERVE, INFOSERVE, LOCALSUBSERVE, RESETTABLE, RESETVERIFY, SEARCHFORM, SEARCHSERVE } from '@/mixins/subject/subject-types';
import { formInfoStore } from '@/store/modules/form';
import XEUtils, { throttle } from 'xe-utils';
import { mergeObjects, paramsData } from '../../publicMethod';
import dayjs, { Dayjs } from 'dayjs';
import { TextQuestion } from '../dynamic-form-base';
const formStore = formInfoStore();

//获取类型
const lookup: any = {
  InputItem,
  InputText,
  InputRadio,
  InputSelect,
  InputSwitch,
  InputCheckbox,
  InputUpload,
  InputTime,
  InputCascader,
  InputRelateBtn,
  InputCustomTable,
  InputCkeditor,
  InputTitle,
  InputIcons
};

//subject变量
let $subscribeSub: Subscription;

const emit = defineEmits(['update:questions']);

const { proxy }: any = getCurrentInstance();
let props: any = defineProps<{ config: ConfigBase<any>; questions: QuestionBase<any>[] }>();

//路由
const $route = router;
const route = useRoute();

//form数据
let rules: any = reactive({});
let ruleForm: any = reactive({});
let dataForm: any = reactive({});
let loading: any = ref(false);
//表单栅格
const formRef = ref<FormInstance>();
const formItemLayout: any = ref({
  labelCol: { span: 4 },
  wrapperCol: { span: props.config.grid ? 24 : 8 }
});

//搜索更多
let isMore: any = ref(props.config.style === 'table-form' ? true : false);

//判断展示更多
let isHiddenMore: any = computed(() => {
  return props.questions.length > 4 || props.questions.length > 24 / props.config.grid ? true : false;
});

//ref校验集合
let handleRefs = ref([]);
const handleRef = (el, question) => {
  if ( ['upload','customTable'].includes(question.controlType)) {
    if( el && question?.key ){
      el.key = question.key;
      let keys = handleRefs.value.map(res=>res.key);
      if(!keys.includes(question.key) ){
        handleRefs.value.push(el);
      }
    }
  }
};

//扩展接口自定义字段
const extendCodes = (dynamicFields = null) => {
  if (dynamicFields) {
    let arr = [];
    let keys = props.questions.map((res) => res.key);
    for (const key in dynamicFields) {
      if (!keys.includes(key)) {
        let obj: any = new TextQuestion({
          key: key,
          label: dynamicFields[key],
          type: 'text',
          state: {}
        });
        arr.push(obj);
      }
    }
    let index = props.questions.map((res) => res.state.name || '').indexOf(props.config.dynamicName) || props.questions.length - 1;
    if (arr.length) {
      props.questions.splice(index + 1, 0, ...arr);
    }
  }
};

onMounted(() => {
  initVerify(); //初始化验证
  //table格式
  if (props.config.style === 'table-form') {
    formItemLayout.value.wrapperCol.span = 20;
  }
  if (props.config.labelCol) {
    formItemLayout.value.labelCol = typeof props.config.labelCol === 'number' ? { span: props.config.labelCol } : props.config.labelCol;
    console.log('配置项看下', formItemLayout.value);
  }
  if (props.config.wrapperCol) {
    formItemLayout.value.wrapperCol = typeof props.config.wrapperCol === 'number' ? { span: props.config.wrapperCol } : props.config.wrapperCol;
  }
  if (!props.config.searchForm) {
    getData(); //请求数据
  }
  subWatch();
  if (props.config.autoSearch) {
    //请求搜索条件
    nextTick(() => {
      search();
    });
  }
});

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
  proxy.$NotificationFormSub.clearParams();
  if (props.config.type === 'layer') {
    formStore.clearLayerFormInfo();
  } else {
    formStore.clearFormInfo();
  }
  reset(false);
});

//子集事件处理
const parentServe = (data: any) => {
  if (!data) return;
  switch (data.key) {
    //从新生层验证
    case 'initVerify':
      initVerify();
      break;
    //单个验证
    case 'isValidateFields':
      isValidateFields(data.value);
      break;
    //从新请求接口
    case 'getData':
      getData();
      break;
      //搜索请求
    case 'autoSearch':
      search();
      break;
  }
};
//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      try {
        if (item.key === RESETVERIFY && item.value.name === 'form') {
          //数据都全部都到了
          initVerify();
        } else if (item.key === SEARCHFORM) {
          if (props.config.name && item.value.name === props.config.name) {
            //搜索功能特用
            search();
          }
        }
      } catch (error) {}
    });
};

//收缩列
const shrinkMethod = (index, item) => {
  let state: boolean = false;
  if (item.state.isMoer) {
    item.state.hiddenKeys = [];
  }
  props.questions.forEach((question, zIndex) => {
    if (zIndex > index && !state) {
      if (question.controlType === 'title') {
        state = true;
      } else {
        if (item.state.isMoer) {
          //存已经隐藏的
          if (question.hidden) {
            item.state.hiddenKeys.push(question.key);
          } else {
            question.hidden = item.state.isMoer;
          }
        } else {
          if (!item.state.hiddenKeys.includes(question.key)) {
            question.hidden = item.state.isMoer;
          }
        }
      }
    }
  });
  //发送subject
  proxy.$NotificationFormSub.pushParams({
    key: DYNAMICTITLESERVE,
    value: {
      label: item.label,
      name: item.state.name || '',
      isMoer: item.state.isMoer,
      index: index
    }
  });
};

//请求表单数据
const getData = () => {
  initVerify();
  if (!props.config.id && props.config.type !== 'layer') {
    let id: any = route.query.id;
    if (id || id === 0) {
      props.config.id = route.query.id;
    }
  }
  if (props.config.data) {
    if (props.config.dynamicFields) {
      extendCodes(props.config.dynamicFields);
    }
    setDataFrom(props.config.data);
    return;
  }
  let msg: any = Object.assign({}, props.config.params || {});
  if (props.config.id) {
    msg = Object.assign(msg, { [props.config.idAsName ? props.config.idAsName : 'id']: props.config.id });
  }

  if (((props.config.id || props.config.id === 0) && props.config.queryUrl) || props.config.noGetDataParams) {
    proxy.$Http
      .api(
        props.config.queryUrl,
        props.config.urlName ? {} : msg,
        props.config.protType ? props.config.protType : 'get',
        props.config.urlParema ? true : false,
        props.config.urlName === 'id' ? props.config.id : props.config.urlName || ''
      )
      .then((data: any) => {
        if (!data) {
          return;
        }
        //动态字段
        extendCodes(data.dynamicFields);

        //给from赋值
        setDataFrom(data.data);
      });
  }
};

//返回from数据
const getDataFrom = () => {
  return Object.assign({}, XEUtils.clone(dataForm, true), XEUtils.clone(ruleForm, true));
};

//给from赋值
const setDataFrom = async (data) => {
  dataForm = data; //存数据
  //处理新增字段
  props.questions.forEach((Question: QuestionBase<any>) => {
    //字段组合
    if (Question.state.keySplit && Question.state.keySplit.length) {
      let arr: any = [];
      if (Question.state.labelSplit && Question.state.labels) {
        let arr2: any = [];
        Question.state.labelSplit.forEach((name: any, index: number) => {
          arr2.push(data[name]);
        });
        Question.state.labels = arr2;
      }
      Question.state.keySplit.forEach((name: any, index: number) => {
        if (Question.type == 'area') {
          arr.push(data[name] + '');
        } else {
          arr.push(data[name]);
        }
      });
      if (arr && arr.length) {
        data[Question.key] = arr;
      }
    }
    //扩展字段赋值
    if (Question.state.extendParams) {
      for (const key in Question.state.extendParams) {
        if (data && data[key] && XEUtils.isObject(data[key]) && !XEUtils.isArray(data[key])) {
          copyFields(data[key], Question.state.extendParams[key]);
        } else {
          Question.state.extendParams[key] = data ? data[key] : Question.state.extendParams[key];
        }
      }
    }
    //类型为对象解析对应value
    if ((Question.controlType === 'select' || Question.controlType === 'radio') && data && data[Question.key] && XEUtils.isObject(data[Question.key]) && data[Question.key].value !== undefined) {
      data[Question.key] = data[Question.key].value;
    }
    //时间格式转换
    if (Question.controlType === 'time') {
      if (typeof data[Question.key] === 'number') {
        data[Question.key] = dayjs(data[Question.key]).format(Question.state.format || 'YYYY-MM-DD HH:mm:ss');
      }
    }
    //存放原始数据作为options
    if( Question.type === 'options' ){
      Question.state.options = data[Question.key];
    }
  });

  //数据前初始化(个性化的处理都要用这个来处理)
  if (props.config.beforeWithMethod && typeof props.config.beforeWithMethod === 'function') {
    data = await props.config.beforeWithMethod(data);
  }
  //临时存一份表单数据
  // dataResult = data;
  if (props.config.type === 'layer') {
    formStore.setLayerFormInfo(data);
    formStore.setLayerQuestions(props.questions, data);
    //pinia数据更新到本地
    emit('update:questions', formStore.getLayerQuestions);
  } else if (props.config.type === 'local') {
    setLocalData(data);
  } else {
    console.log('from里面的赋值');
    formStore.setFormInfo(data);
    formStore.setQuestions(props.questions, data);
    initVerify();
    //pinia数据更新到本地
    emit('update:questions', formStore.getQuestions);
  }

  //请求成功后发一个完成通知
  proxy.$NotificationFormSub.pushParams({
    key: INFOSERVE,
    value: data
  });
};

//本地数据赋值
const setLocalData = (data) => {
  // let newQuestion: any = XEUtils.clone(props.questions, true);
  if (data && props.questions && props.questions.length) {
    props.questions.forEach((question: any) => {
      for (let key in data) {
        if (question.key.includes('.')) {
          let keys: any = question.key.split('.');
          if (data[keys[0]]) {
            question.value = keys.reduce((acc, curr) => acc[curr], data);
          } else {
            question.value = '';
          }
        } else if (key == question.key) {
          question.value = data[key];
        }
      }
    });
    // emit('update:questions', newQuestion);
  }
};

//类型处理
const typeFilter = (val: any) => {
  if (val === 'true') {
    return true;
  } else if (val === 'false') {
    return false;
  }
  return val;
};

//列表搜索
const search = () => {
  let msg: any = {
    // pageNumber: 1,
    // pageSize: 20,
  };
  if (props.config.params) {
    msg = Object.assign(msg, props.config.params);
  }

  props.questions.forEach((Question: QuestionBase<any>) => {
    if (Question.hidden) {
      return;
    }
    msg[Question.key] = typeFilter(Question.value);

    //字段拆分
    if (Question.state.keySplit && Question.state.keySplit.length && Array.isArray(Question.value)) {
      Question.state.keySplit.forEach((name: any, index: number) => {
        msg[name] = Question.value[index] || '';
      });
    }
    //扩展字段
    if (Question.state.extendParams) {
      for (const key in Question.state.extendParams) {
        if (Question.state.extendParams[key]) {
          msg[key] = Question.state.extendParams[key];
        }
      }
    }
  });

  // 删除空字段
  if (msg) {
    Object.keys(msg).forEach((key) => {
      if (!msg[key] && msg[key] !== 0 && msg[key] !== false) {
        delete msg[key];
      }
    });
  }

  //校验
  isValidateFields()
    .then((res) => {
      //提交拦截
      if (props.config.combinationMethod && typeof props.config.combinationMethod === 'function') {
        msg = props.config.combinationMethod(msg);
      }
      if (!msg) {
        return false;
      }

      //发送subject
      proxy.$NotificationFormSub.pushParams({
        key: SEARCHSERVE,
        value: msg,
        state: {
          name: props.config.name
        }
      });
    })
    .catch((err) => {});
};

//返回地址
const back = () => {
  // 存在指定返回的url的情况
  if (props.config.backName) {
    //如果有返回参数，则返回上一页自动带上去
    if (props.config.backParams) {
      proxy.$goTo(props.config.backName, props.config.backParams);
    } else {
      if (props.config.backName === $route.currentRoute.value.name) {
        getData();
      } else {
        proxy.$goTo(props.config.backName);
      }
    }
    return;
  }

  //如果是弹层就关闭弹层
  if (props.config.type === 'layer') {
    layerClear();
    return;
  }

  // 默认返回上一页
  router.back();
};

//子组件自己的校验
const subsetVerify = () => {
  let state = true;
  handleRefs.value.forEach((item) => {
    if (XEUtils.isFunction(item.submitVerify)) {
      if (!item.submitVerify()) {
        state = false;
      }
    }
  });
  return state;
};
//调用子组件方法
const invokeMethodRef = (key, methodName, value = null) => {
  let newValue = null;
  handleRefs.value.forEach((item) => {
    if (item.key === key) {
      //自定义table的ref
      if (value) {
        //方法
        item[methodName](value);
      } else {
        //获取
        newValue = item[methodName];
      }
    }
  });
  if (!value) {
    return newValue;
  }
};

const isValidateFields = async (keys: any = null) => {
  props.questions.forEach((question: any) => {
    if (question.hidden && rules[question.key]) {
      rules[question.key].forEach((rul) => {
        delete rules[question.key]
      });
    }
  });
  return await formRef.value.validateFields(keys);
};

//提交表单且数据验证成功后回调事件

const onFinish = throttle(async (fn = null, skipValidate = false) => {
  if (loading.value) return;
  loading.value = true;
  isValidateFields(skipValidate ? [] : null)
    .then((res) => {
      //各组件的验证
      if (!skipValidate && !subsetVerify()) {
        // message.error('请填写正确格式');
        loading.value = false;
        return false;
      }

      loading.value = true;

      let msg: any = XEUtils.clone(props.config.params, true) || {};
      if (props.config.data) {
        msg = Object.assign(msg, XEUtils.clone(props.config.data));
      }
      //遍历赋值
      props.questions.forEach((Question: QuestionBase<any>) => {
        if (Question.hidden && Question.key !== 'id') {
          return;
        }
        //给当前值赋值
        if (Question.key.includes('.')) {
          let keys: any = Question.key.split('.');
          let lastKey = keys.pop();
          keys.reduce((acc, cur) => {
            if (!acc[cur]) {
              acc[cur] = {};
            }
            return acc[cur];
          }, msg)[lastKey] = Question.value;
        } else {
          msg[Question.key] = Question.value;
        }
        //自定义table选择功能
        if (Question.state.selectedRowKeys) {
          msg[Question.key] = Question.value.filter((res) => Question.state.selectedRowKeys.includes(res[Question.state.rowKey ? Question.state.rowKey : 'id']));
        }
        //替换当前key
        if (Question.asKey) {
          msg[Question.asKey] = typeFilter(Question.value);
        }
        //字段拆分
        if (Question.state.keySplit && Question.state.keySplit.length && Array.isArray(Question.value)) {
          Question.state.keySplit.forEach((name: any, index: number) => {
            msg[name] = Question.value[index] || '';
          });
          delete msg[Question.key];
        }
        //省市区存名称
        if (Question.state.labelSplit && Question.state.labels) {
          Question.state.labelSplit.forEach((name: any, index: number) => {
            msg[name] = Question.state.labels[index] || '';
          });
        }
        //radio的label输入值扩展到外面
        if (Question.optionsValue) {
          Question.options.forEach((item: any) => {
            if (item.key) {
              msg[item.key] = item.typeValue;
            }
          });
        }
        //扩展字段
        if (Question.state.extendParams) {
          for (const key in Question.state.extendParams) {
            msg[key] = Question.state.extendParams[key];
          }
        }
        //自定义参数从选中的state.selectValue数据里面按照对应state.selectParams进行拼接参数，组件只需要设置state.selectParams规则
        if( Question.state.selectParams && Question.state.selectValue && Question.state.selectValue.length ){
          let arr = [];
          arr = Question.state.selectValue.map((res)=>(paramsData(res,{ params: Question.state.selectParams })));
          console.log('多选拼接数据',arr);
          msg[Question.key] = arr;
        }
      });

      //新增、更新区别
      if (props.config.id || props.config.id == 0 || props.config.urlName) {
        let obj = Object.assign({}, props.config.type === 'layer' ? formStore.getLayerFormInfo : formStore.getFormInfo);
        mergeObjects(obj, msg);
        msg = obj;
      }

      //公共确认密码
      if (msg.repassword && msg.password) {
        if (msg.repassword !== msg.password) {
          message.warning('2次输入的密码不一样请重新输入');
          loading.value = false;
          return;
        }
      }
      delete msg.repassword;

      //提交拦截处理
      if (props.config.combinationMethod && typeof props.config.combinationMethod === 'function') {
        msg = props.config.combinationMethod(msg);
      }
      if (!msg) {
        loading.value = false;
        return false;
      }

      //获取数据返回
      if (fn) {
        fn(msg);
        loading.value = false;
        return;
      }

      //丢给本地提交
      if (props.config.localSub) {
        proxy.$NotificationFormSub.pushParams({
          key: LOCALSUBSERVE,
          value: msg,
          state: {
            name: props.config.name
          }
        });
        loading.value = false;
        return;
      }

      //接口提交
      proxy.$Http.api(props.config.updateUrl ? props.config.updateUrl : props.config.addUrl, msg, props.config.portType ? props.config.portType : 'post').then((data: any) => {
        if (data.success) {
          loading.value = false;
          message.success('提交成功！');
          //类型为弹层的处理
          if (props.config.type === 'layer') {
            layerClear();
            proxy.$NotificationFormSub.pushParams({
              key: RESETTABLE,
              value: {
                name: props.config.name,
                params: msg,
                data: data.data
              }
            });
          } else {
            back();
          }
        } else {
          loading.value = false;
        }
      })
    })
    .catch((err) => {
      initVerify();
      onFinishFailed(err);
      loading.value = false;
      return Promise.reject(err);
    });
},3000);

//提交表单且数据验证失败后回调事件
const onFinishFailed = (errorInfo: any) => {
  if( errorInfo && errorInfo.errorFields ){
    message.error(errorInfo.errorFields[0].errors[0] || '请检查必填项');
  }
  console.log('错误信息',errorInfo);
};

//动态生层组件名称
const tagName = (name: string) => {
  let str = 'Input';
  str += name.substring(0, 1).toUpperCase() + name.substring(1);
  return markRaw(lookup[str]);
};

//初始化验证
const initVerify = () => {
  //给ruleForm赋值
  props.questions.forEach((Question: QuestionBase<any>) => {
    ruleForm[Question.key] = Question.value;
    rawVerify(Question);
  });
};

//生层规则
const rawVerify = (Question: QuestionBase<any>) => {
  let obj: any = {};
  obj.required = Question.required ? true : false;
  obj.message = Question.prompt;
  obj.trigger = ['input', 'item', 'textarea'].indexOf(Question.controlType) !== -1 ? 'blur' : 'change';
  if (Question.controlType === 'color') {
    obj.trigger = 'active-change';
  }
  if (Question.reg) {
    const reg: any = Question.reg;
    if (typeof reg == 'function') {
      // 自定义校验
      delete obj.message;
      obj.validator = async (rule, value) => {
        return reg(rule, value, ruleForm, formRef);
      };
    } else {
      obj.pattern = reg;
    }
  }

  if ((!obj.required && !obj.pattern) || obj.hidden) {
    delete rules[Question.key];
    return false;
  }

  rules[Question.key] = [obj];
};

//重置
const reset = (isSearch = true) => {
  props.questions.forEach((Question) => {
    if (Array.isArray(Question.value)) {
      Question.value = [];
    } else if (Question.value === null) {
      Question.value = null;
    } else if (typeof Question.value === 'object') {
      Question.value = {};
    } else {
      Question.value = null;
    }
    //扩展字段
    if (Question.state.extendParams) {
      for (const key in Question.state.extendParams) {
        Question.state.extendParams[key] = null;
      }
    }
  });
  console.log('重置', props.questions);
  isSearch && search();
};

//如果是弹层的from就要清除弹层
const layerClear = () => {
  proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR, value: { name: 'form' } });
};

//拷贝对象对应的key
function copyFields(objA, objB) {
  for (let key in objB) {
    if (objA.hasOwnProperty(key)) {
      objB[key] = objA[key];
    }
  }
}

//组件对外公开方法
defineExpose({
  initVerify,
  isValidateFields, //验证
  onFinish, //提交表单
  getData, //请求接口数据
  getDataFrom, //获取数据
  reset,
  search,
  ruleForm,
  invokeMethodRef
});
</script>
<style lang="less" scoped>
@import url('./dynamic-form.component.less');
</style>
